<?php


namespace App\Admin\Extensions\Form;


use App\Model\Upload;
use Encore\Admin\Form\Field\File;

class UploadFile extends File
{

    protected $view = 'admin::form.file';

    public function prepare($image)
    {
        if (request()->has(static::FILE_DELETE_FLAG)) {
            return $this->destroy();
        }

        $this->name = $this->getStoreName($image);

        $path = $this->uploadAndDeleteOriginal($image);

        $data = [
            'disk'=>config('admin.upload.disk'),
            'filename'=>$image->getClientOriginalName(),
            'path'=>dirname($path),
            'fullname'=>$path,
            'mimetype'=>$image->getMimeType(),
            'filesize'=>$image->getSize(),
        ];
        $upload = new Upload;
        $upload->fill($data);
        $upload->save();
        return $upload->id;

    }

    public function render()
    {
        $value = $this->value();
        $newValue = Upload::where('id',$value)->value('fullname');
        if($newValue){
            $this->value($newValue);
        }
        return parent::render();
    }
}
